<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>信息列表</title>
</head>
<body>
<h1>老师修改信息页面</h1>

<form id="teaInfo" enctype="multipart/form-data">

    账号：<input id="username"><br/>
    姓名：<input type="text" name="name" id="name"/><br/>
    年龄：<input type="text" name="age" id="age"/><br/>
    性别：
    <input type="radio" name="sex" value="man" />男
    <input type="radio" name="sex" value="woman" />女
    <br/>
    学科：
    <select name="courseId" id="courseId">

    </select>
    <br/>
    上传头像：<input type="file" name="photo"/><br/>

    <input type="submit" value="修改"/>
    <input type="button" value="返回" onclick="goIndex()"/>
</form>

<script src="js/jquery-1.8.2.js"></script>
<script type="text/javascript">
    function goIndex(){
        window.location = "index.html";
    }

    $(function () {

        $.ajax(
            {
                type: "post",
                url: "teacher?action=doInitModify",
                async: true,
                success: function (data) {

                    const info = eval("("+data+")")
                    const teacher = eval("("+info.teacher+")")
                    const courses = eval("("+info.courses+")")//解析object

                    for (const course of courses) {
                        const option = $("<option></option>").attr("value",`${course.id}`).text(`${course.name}`)
                        $("#courseId").append(option)
                    }


                    $("#username").val(teacher.username).attr("readonly", "readonly")
                    $("#name").val(teacher.name)
                    $("#age").val(teacher.age)

                    $("input[name=sex]").each(function () {
                        if ($(this).val() == teacher.sex) {
                            $(this).attr("checked", "checked")
                        }
                    })



                }
            }
        )


        $("#teaInfo").submit(function (event) {//修改功能
            event.preventDefault();
            // 创建 FormData 对象
            let formData = new FormData(this);
            $.ajax(
                {
                    type:"post",
                    url:"teacher?action=doModify",
                    async:true,
                    data: formData,
                    processData: false,
                    contentType: false,
                    success:function (data){
                        if (data == "1"){
                            alert("修改成功");
                            window.location = "index.html";
                        }else if (data == "-1"){
                            alert("修改失败");
                        }
                    }
                }
            )
        })
    })

</script>

</body>
</html>